package java_thinking.unit_21._21_6;

import java.util.*;
import java.util.concurrent.*;

/**
 * @Desc:
 * @author: cww
 * @DateTime: 2019/6/13 8:36
 */

public class TimeBudget2 {
    private static ExecutorService exec = Executors.newCachedThreadPool();
    public List<TravelQuote> getRankedTravelQuote(TravelInfo info,
                                                  Set<TravelCompany> companies,
                                                  Comparator<TravelQuote> ranking,
                                                  long time, TimeUnit unit) throws InterruptedException {
        List<QuoteTask> tasks = new ArrayList<>();
        for (TravelCompany company : companies) {
            tasks.add(new QuoteTask(company,info));
        }
        List<Future<TravelQuote>> futures = exec.invokeAll(tasks, time,unit);
        List<TravelQuote> quotes = new ArrayList<>(tasks.size());
        Iterator<QuoteTask> iterator = tasks.iterator();
        for (Future<TravelQuote> future : futures) {
            QuoteTask task = iterator.next();
            try {
                quotes.add(future.get());
            } catch (ExecutionException e) {
                quotes.add(task.getFailureQuote(e.getCause()));
            } catch (CancellationException e) {
                quotes.add(task.getTimeoutQuote(e));
            }
        }
        Collections.sort(quotes,ranking);
        return quotes;
    }
}
